package com.android.basekt.viewmodel

import android.view.View
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.android.basekt.base.BaseViewEventConstants
import com.android.basekt.base.LifecycleObseverImp
import com.android.basekt.base.SimpleViewEvent
import com.android.basekt.base.ViewEvent
import com.dinero.pagecontents.bean.ApiResponse
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch

open class BaseViewModel :
    ViewModel(), LifecycleObseverImp {

    open var mTitleContent = MutableLiveData<String>()

    val mViewEvents = MutableLiveData<ViewEvent>()

    private val uiScope = viewModelScope

    suspend fun <T> netApi(job: suspend () -> T): ApiResponse<T> {
        return try {
            ApiResponse(job())
        } catch (e: java.lang.Exception) {
            ApiResponse(e)
        }
    }

    fun launch(block: suspend CoroutineScope.() -> Unit): Job {
        return uiScope.launch {
            try {
                block()
            } catch (e: Exception) {

            }
        }
    }

    override fun onCreat() {}

    override fun onResume() {
        android.util.Log.i(TAG, "onResume:==>")
    }

    override fun onPause() {
        android.util.Log.i(TAG, "onPause:===> ")
    }

    override fun onFinish() {
        android.util.Log.i(TAG, "onFinish:===>")
    }


    companion object {
        private const val TAG = "BaseViewModel"
    }

    fun <Event : ViewEvent> Event.publish() {
        mViewEvents.value = this
    }

    fun Int.publish() {
        mViewEvents.value = SimpleViewEvent(this)
    }


    open fun finishView() {
        BaseViewEventConstants.FINISH_VIEW.publish()
    }

    fun hideInputKeyboard(view: View) {
        BaseViewEventConstants.HIDE_KEYBOARD_VIEW.publish()
    }
}

